package com.personal.aspect;

import com.personal.utils.IpUtils;
import com.personal.utils.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Aspect
@Component
@Slf4j
public class PageViewAspect {

    @Autowired
    private RedisUtils redisUtils;

    @Pointcut("@annotation(com.personal.annotation.PageView)")
    public void PageViewAspect(){
    }

    /**
     * 切入处理
     * @param joinPoint
     * @return
     */
    @Around("PageViewAspect()")
    public Object around(ProceedingJoinPoint joinPoint){
        Object[] objects = joinPoint.getArgs();
        Object resourcesId = objects[0];
        log.info("资源id为:{}", resourcesId);
        Object obj = null;
        try {
            //将ip作为redis中的值
            String ipAddr = IpUtils.getIpAddr();
            log.info("ip地址为:{}", ipAddr);
            //redis中的key
            String key = "resourcesId_" + resourcesId;
            Long num = redisUtils.add(key, ipAddr);
            if (num == 0){
                log.info("该ip:{}，访问浏览量已经增加过了",ipAddr);
            }
            obj = joinPoint.proceed();

        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        return obj;
    }


}
